import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Select, Cascader } from 'antd';
import { connect } from 'dva';
import { formatMessage } from 'umi-plugin-react/locale';
import { isString } from 'util';

@connect(({ }) => ({}))
export default class AntdSelectRegion extends Component {
    static propTypes = {
        isParent: PropTypes.bool
    }
    static defaultProps = {
        isParent: true, //是否展示当前父层级
    }
    constructor(props) {
        super(props);
        this.state = {
            selected: undefined,
            options: [],
            isFirst: true,
            selectValueForView: [], //获取展示的name集合
        };
    }

    componentDidMount() {
        this.setValue(this.props);
    }

    componentWillReceiveProps(nextProps) {
        const { value, refresh } = nextProps;
        if (JSON.stringify(this.props.value) !== JSON.stringify(value)) {
            this.setValue(nextProps);
        }
    }

    //只有手动选中的区域需要去查，父级传的数据默认有省市区名称
    getSelectValueOfName = (data, num, lable = []) => {
        const { getRegionName } = this.props;
        const { options, selected } = this.state;
        const arr = data || options;
        arr.forEach((v, index) => {
            if (selected && v.value === selected[num]) {
                this.setState({
                    selectValueForView: lable.concat(v.label)
                });
                if (v.children && num < (selected.length - 1)) {
                    this.getSelectValueOfName(v.children, num + 1, lable.concat(v.label));
                } else {

                    const names = lable.concat(v.label).join('/')
                    getRegionName && getRegionName(names);
                }
                return;
            }
        })
    }

    //编辑时回显调用的方法
    setValue = props => {
        const { value, isParent, split, filter, form } = props;
        const { options } = this.state;
        let newData = [];
        if (value && isString(value)) {
            let data = value.split(split);
            if (isParent) {
                if (!filter) {
                    data = ['', ...data]; //加油一个空的目的为了过滤掉最后一层级
                }
                // newData = data.filter((_, index) => index !== 0 && index !== data.length - 1);
                newData = data.filter((_, index) => index !== 0);

                // this.onChange(newData, null);
                this.setState({
                    selected: newData,
                });
                this.queryRegion(2, data);
            }
        } else {
            this.setState({ selected: value });
        }
    };

    //查询接口返回数据：
    queryRegion = (index, selectedData) => {
        const { label, isParent, limitLevel } = this.props;
        this.queryById({
            id: selectedData[index],
            callback: data => {
                const length = isParent ? 2 : 2;
                if (index === selectedData.length - length) {
                    const newOptions = data.map(item => {
                        let hasChild = false;
                        if ((item.childNumber !== undefined && item.childNumber === 0)) {
                            hasChild = true;
                        }
                        if (limitLevel) {
                            hasChild = item.level == limitLevel ? true : false;
                        }
                        return {
                            value: item.id,
                            label: item[label],
                            isLeaf: hasChild,
                        };
                    });
                    this.setState({
                        options: newOptions,
                    });
                } else {
                    const targetOptions = data.map(item => {
                        let hasChild = false;
                        if ((item.childNumber !== undefined && item.childNumber === 0)) {
                            hasChild = true;
                        }
                        if (limitLevel) {
                            hasChild = item.level == limitLevel ? true : false;
                        }
                        if (item.id === selectedData[index + 1]) {
                            return {
                                value: item.id,
                                label: item[label],
                                isLeaf: hasChild,
                                children: this.state.options,
                            };
                        } else {
                            return {
                                value: item.id,
                                label: item[label],
                                isLeaf: hasChild,
                            };
                        }
                    });
                    this.setState({
                        options: targetOptions,
                    });
                }
                if (--index >= 0) {
                    this.queryRegion(index, selectedData);
                }
            },
        });
    };
    onBlur = () => {
        const { selected } = this.state;
        const { limitLevel } = this.props;
        //可以选择省市， 或者 省市区
        if (selected && limitLevel && (selected.length !== Number(limitLevel) && selected.length !== Number(limitLevel) - 1)) {
            this.setState({
                selected: undefined
            })
            this.triggerChange();
        }

    }

    onFocus = () => {
        const { dispatch, url, label, filter, limitLevel, defaultId } = this.props;
        const { options } = this.state;
        if (options.length > 0) return;
        this.queryById({
            id: defaultId ? defaultId : '',
            callback: data => {
                if (!data) return;
                this.firstId = data[0].id;
                // filter ：是否过滤当前层级（用于展示上级区域）
                if (filter) {
                    this.queryById({
                        id: data[0].id,
                        callback: data2 => {
                            if (!data2) return;
                            this.setState({
                                options: data2.map(item => {
                                    let hasChild = false;
                                    if ((item.childNumber !== undefined && item.childNumber === 0)) {
                                        hasChild = true;
                                    }
                                    return {
                                        value: item.id,
                                        label: item[label],
                                        isLeaf: hasChild,
                                    };
                                }),
                            });
                        },
                    });
                } else {
                    this.setState({
                        options: data.map(item => {
                            let hasChild = false;
                            if ((item.childNumber !== undefined && item.childNumber === 0)) {
                                hasChild = true;
                            }
                            if (limitLevel) {
                                hasChild = item.level == limitLevel ? true : false;
                            }
                            return {
                                value: item.id,
                                label: item[label],
                                isLeaf: hasChild,
                            };
                        }),
                    });
                }
            },
        });
    };

    /**
     * 查询options 接口
     */
    queryById = ({ id, callback } = {}) => {
        const { dispatch, url, paramsLabel, requestType, defaultId } = this.props;
        let newUrl = url;
        const newId = id || defaultId;
        let params = { [paramsLabel]: id };
        if (requestType == "get") {
            if (!newId) return
            newUrl = `${url}/${newId}`;
            params = {};
        }
        dispatch({
            type: 'common/selectReginList',
            payload: {
                params,
                url: newUrl,
            },
            callback: data => {

                if (!data) return;
                callback(data);
            },
        });
    };

    /**
     * 选中加载数据
     */
    loadData = selectedOptions => {
        const { dispatch, label, limitLevel } = this.props;
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;
        this.queryById({
            id: targetOption.value,
            callback: data => {
                if (!data) return;
                targetOption.loading = false;
                if (data.length === 0) {
                } else {
                    targetOption.children = data.map(item => {
                        let hasChild = false;
                        if ((item.childNumber !== undefined && item.childNumber === 0)) {
                            hasChild = true;
                        }
                        if (limitLevel) {
                            hasChild = item.level == limitLevel ? true : false;
                        }
                        return {
                            value: item.id,
                            label: item[label],
                            isLeaf: hasChild,
                        };
                    });
                }
                this.setState({
                    options: [...this.state.options],
                });
            },
        });
    };

    triggerChange = value => {
        const onChange = this.props.onChange;
        if (onChange) {
            onChange(value);
        }
    };
    //显示/隐藏浮层的回调
    onPopupVisibleChange = value => {
        const { isFirst } = this.state;
        if (!value) {
            this.setState({ isFirst: true });
            setTimeout(() => {
                this.getSelectValueOfName(undefined, 0)
            }, 0)
        }
    };
    /**
     * 值改变
     */
    onChange = keys => {
        this.setState({ selected: keys });
        this.triggerChange(keys);
    };

    filter = (inputValue, path) => {
        //some检测数组有满足的一个就返回true
        return path.some(option => {
            if (option.children) {
                return false;
            }
            return option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1;
        });
    };

    render() {
        const { selected, options, selectValueForView } = this.state;
        const { disabled } = this.props;
        return (
            <Cascader
                onFocus={this.onFocus}
                onBlur={this.onBlur}
                allowClear={true}
                options={options}
                loadData={this.loadData}
                onPopupVisibleChange={value => {
                    this.onPopupVisibleChange(value);
                }}
                disabled={disabled}
                value={selected}
                onChange={this.onChange}
                // displayRender={label => label.join(' / ')} //默认就是
                placeholder={formatMessage({ id: 'form.select.placeholder' })}
                changeOnSelect
            />
        );
    }
}
